from django.utils.deprecation import MiddlewareMixin
from timeholder import models
from django.conf import settings
from django.shortcuts import redirect

class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户已经登录，则request中赋值"""
        # 获取session中的username
        user_name = request.session.get('username')
        print(user_name)
        # 获取用户名对应的对象user_obj
        user_obj = models.UserInfo.objects.filter(username=user_name).first()
        print(user_obj)
        # 赋值给request中存储，方便后续读取
        request.user_obj = user_obj

        # 如果在白名单中，则通过
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # 如果没有登录且不在白名单中，则跳转到登录页面
        if not user_obj:
            return redirect('/login/')
